//
//  AddAlarmClockViewController.m
//  AlarmClock
//
//  Created by apple on 16/9/28.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "AddAlarmClockViewController.h"
#import "BSKConsts.h"
#import "AddCustomTableViewCell.h"
#import "SDAutoLayout.h"
#import "PublicView.h"
#import "LabelView.h"
#import "MultiSelectedView.h"
#import "UILocalNotification+setAlarmclock.h"
#import "BSKSington.h"
@interface AddAlarmClockViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) UIButton *cancelButton;
@property (nonatomic,strong) UIButton *sureButton;
@property (nonatomic,strong) UILabel *titleLabel;
@property (nonatomic,strong) UIDatePicker *datePicker;
@property (nonatomic,strong) NSArray *titleDataSource;
@property (nonatomic,strong) NSArray *repeatArray;
@property (nonatomic,strong) NSString *repeatString;
@property (nonatomic,strong) NSString *labelString;
@property (nonatomic,strong) NSString *bellString;
@property (nonatomic,strong) UIButton *deleteButton;
@property (nonatomic,strong) NSDictionary *dic;
@property (nonatomic,strong) UIImageView * bgImageView;
@property (nonatomic,strong) NSArray *bellArray;

@property (nonatomic,strong) NSMutableArray *alarmClockArray;

@end

@implementation AddAlarmClockViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeAperance];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    NSMutableArray *array = [[[NSUserDefaults standardUserDefaults] objectForKey:@"alarmClock"] mutableCopy];
    if (self.isSelected) {
        NSDictionary *dic = array[self.index];
        NSString *dateString = dic[@"date"];
        //设置时间输出格式
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"HH:mm"];
        NSDate *date = [formatter dateFromString:dateString];
        [self.datePicker setDate:date animated:YES];
    }
    
}
- (void)initializeAperance {
    self.view.backgroundColor = [UIColor grayColor];
    self.bgImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"bg2.jpeg"]];
    [self.view addSubview:self.bgImageView];
    self.bgImageView.sd_layout
    .leftSpaceToView(self.view,0)
    .topSpaceToView(self.view,0)
    .rightSpaceToView(self.view,0)
    .bottomSpaceToView(self.view,0);    
    self.titleDataSource = @[@"重复",@"铃声",@"标签"];
    self.alarmClockArray = @[].mutableCopy;
    [self.view addSubview:self.titleLabel];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.cancelButton];
    [self.view addSubview:self.sureButton];
    UIView * dateBgView = [[UIView alloc]init];
    [self.view addSubview:dateBgView];
    [self.view addSubview:self.datePicker];
    self.cancelButton.sd_layout
    .leftSpaceToView(self.view,20)
    .topSpaceToView(self.view,30)
    .widthIs(ScreenWidth/8)
    .heightEqualToWidth();
    
    self.sureButton.sd_layout
    .rightSpaceToView(self.view,20)
    .topSpaceToView(self.view,30)
    .widthIs(ScreenWidth/8)
    .heightEqualToWidth();
    
    self.titleLabel.sd_layout
    .centerXIs(self.view.centerX)
    .topSpaceToView(self.view,25)
    .widthIs(ScreenWidth / 3)
    .heightIs(30);
    
    
    dateBgView.backgroundColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.6];
    dateBgView.layer.shadowColor = [UIColor blackColor].CGColor;
    dateBgView.layer.shadowOffset = CGSizeMake(10, 10);
    dateBgView.layer.shadowOpacity = 0.8;
    dateBgView.layer.cornerRadius = 20;
    dateBgView.sd_layout
    .centerXIs(self.view.centerX)
    .topSpaceToView(self.titleLabel,60)
    .widthIs(ScreenWidth/1.5)
    .heightIs(ScreenHeight / 4);
    self.datePicker.sd_layout
    .centerXIs(self.view.centerX)
    .topSpaceToView(self.titleLabel,60)
    .widthIs(ScreenWidth/1.5)
    .heightIs(ScreenHeight / 4);
    
    self.tableView.sd_layout
    .topSpaceToView(dateBgView,30)
    .leftSpaceToView(self.view,0)
    .rightSpaceToView(self.view,0)
    .bottomSpaceToView(self.view,0);
    
}

#pragma mark - action
- (void)cancelButtonPressed:(UIButton *)sender {
//    [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
    [[BSKSington sharBSKSington].rootViewController popViewControllerAnimated:YES];
}

- (void)sureButtonPressed:(UIButton *)sender {
    //获取当前时间控件的日期和时间
    NSDate *selected = [self.datePicker date];
    //设置时间输出格式
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    //[formatter setDateFormat:@"HH : mm"];
    [formatter setDateFormat:@"HH:mm"];
    NSString *currentDate = [formatter stringFromDate:selected];
    
    // 将当前时间转换成时间戳 用来唯一标示闹钟信息
    NSDate *currentDate1 = [NSDate date];
    NSTimeInterval timeInterval = [currentDate1 timeIntervalSince1970];
    NSString *timeString = [NSString stringWithFormat:@"%d",(int)timeInterval];
    
    NSDictionary *dic = @{@"alarmClockId":timeString,@"date":currentDate,@"bell":self.bellString,@"repeat":self.repeatString,@"isStart":@"YES",@"label":self.labelString};
    
//    [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
    
    [[BSKSington sharBSKSington].rootViewController popViewControllerAnimated:YES];
    
    if ([self.titleLabel.text isEqualToString:@"编辑闹钟"]) {
        // 本地数据持久化
        NSMutableArray *array = [[[NSUserDefaults standardUserDefaults] objectForKey:@"alarmClock"] mutableCopy];
        NSString *switchEdit = array[self.index][@"isStart"];
        NSString *alarmClock = array[self.index][@"alarmClockId"];
        
        NSMutableDictionary *dic1 = [dic mutableCopy];
        [dic1 setObject:alarmClock forKey:@"alarmClockId"];
        [dic1 setObject:switchEdit forKey:@"isStart"];
        
        [array removeObjectAtIndex:self.index];
        NSDictionary *newDic = [dic1 copy];
        [array insertObject:newDic atIndex:self.index];
        
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"alarmClock"];
        [[NSUserDefaults standardUserDefaults] setObject:array forKey:@"alarmClock"];
        
        if ([switchEdit isEqualToString:@"YES"]) {
            // 关闭闹钟
            NSArray * notis = [UIApplication sharedApplication].scheduledLocalNotifications;
            for (UILocalNotification * noti in notis) {
                NSString * type = noti.userInfo[@"type"];
                if ([[noti.userInfo objectForKey:@"alarmClockId"] isEqualToString:newDic[@"alarmClockId"]]&&!type) {
                    [[UIApplication sharedApplication] cancelLocalNotification:noti];
                }
            }
            // 重新发送通知
            [UILocalNotification createAlrmClockWhithInfoDic:newDic];
        }
    } else {
        NSMutableArray *array1 = [[[NSUserDefaults standardUserDefaults] objectForKey:@"alarmClock"] mutableCopy];
        if (array1.count > 0) {
            for (NSDictionary *dic in array1) {
                [self.alarmClockArray addObject:dic];
            }
            [self.alarmClockArray addObject:dic];
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"alarmClock"];
            [[NSUserDefaults standardUserDefaults] setObject:self.alarmClockArray forKey:@"alarmClock"];
            
        } else {
            [self.alarmClockArray addObject:dic];
            [[NSUserDefaults standardUserDefaults] setObject:self.alarmClockArray forKey:@"alarmClock"];
        }
        // 发送本地通知
        [UILocalNotification createAlrmClockWhithInfoDic:dic];
    }
    
}


- (void)deleteButtonPressed:(UIButton *)sender {
    // 获取所有闹钟
    NSMutableArray *array = [[[NSUserDefaults standardUserDefaults] objectForKey:@"alarmClock"] mutableCopy];
    NSDictionary *dic = array[self.index];
    if ([dic[@"isStart"] isEqualToString:@"YES"]) {
        // 关闭闹钟
        NSArray * notis = [UIApplication sharedApplication].scheduledLocalNotifications;
        for (UILocalNotification * noti in notis) {
            if ([[noti.userInfo objectForKey:@"alarmClockId"] isEqualToString:dic[@"alarmClockId"]]) {
                [[UIApplication sharedApplication] cancelLocalNotification:noti];
            }
        }
    }
    [array removeObjectAtIndex:self.index];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"alarmClock"];
    // 重新存储闹钟信息
    [[NSUserDefaults standardUserDefaults] setObject:array forKey:@"alarmClock"];
    
//    [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
    
    [[BSKSington sharBSKSington].rootViewController popViewControllerAnimated:YES];
}

#pragma mark - delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.titleDataSource.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"addAlarmClock";
    AddCustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[AddCustomTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.titleLabel.text = self.titleDataSource[indexPath.row];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    NSMutableArray *array = [[[NSUserDefaults standardUserDefaults] objectForKey:@"alarmClock"] mutableCopy];
    if (array.count > 0) {
        self.dic = array[self.index];
    }
    if (indexPath.row == 0) {
        if (array.count > 0) {
            if ([self.dic[@"repeat"] isEqualToString:@"星期日|星期一|星期二|星期三|星期四|星期五|星期六"])
            {
                cell.detailLabel.text = @"每天";
            } else if ([self.dic[@"repeat"] isEqualToString:@"星期一|星期二|星期三|星期四|星期五"])
            {
                cell.detailLabel.text = @"周一到周五";
            } else {
                cell.detailLabel.text = self.dic[@"repeat"];
            }
            self.repeatString = self.dic[@"repeat"];
            //cell.detailLabel.text = self.dic[@"repeat"];
        } else {
            cell.detailLabel.text = @"只响一次";
            self.repeatString = cell.detailLabel.text;
        }
        
        
    }
    if (indexPath.row == 1) {
        if (array.count > 0) {
            cell.detailLabel.text = self.dic[@"bell"];
        } else {
            cell.detailLabel.text = @"起床歌";
        }
        self.bellString = cell.detailLabel.text;
    }
    
    if (indexPath.row == 2) {
        if (array.count > 0) {
            cell.detailLabel.text = self.dic[@"label"];
        } else {
            cell.detailLabel.text = @"闹钟";
        }
        self.labelString = cell.detailLabel.text;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    __weak typeof(self) weakSelf = self;
    self.repeatArray = @[@"只响一次",@"周一到周五",@"每天",@"自定义"];
    self.bellArray = @[@"起床歌",@"容嬷嬷叫你起床",@"起床号",@"清晨",@"fallbackring",@"ring"];
    if (indexPath.row == 0) {
        PublicView *public = [[PublicView alloc]initWithFrame:self.view.bounds];
        //-------
        public.controller = weakSelf;
        AddCustomTableViewCell * cell = (AddCustomTableViewCell * )[_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
        [public setSelectedCallback:^(NSInteger index,__weak PublicView *view) {
            if (index!=3) {
                cell.detailLabel.text = weakSelf.repeatArray[index];
            }
            if ([weakSelf.repeatArray[index] isEqualToString:@"周一到周五"]) {
                weakSelf.repeatString = @"星期一|星期二|星期三|星期四|星期五";
            }
            if (index == 2) {
                weakSelf.repeatString = @"星期日|星期一|星期二|星期三|星期四|星期五|星期六";
            }
            if (index == 0) {
                weakSelf.repeatString = @"只响一次";
            }
            if ([view.titleLabel.text isEqualToString:@"重复"]) {
                if (index != 3) {
                    [view removeSelf];
                } else {
                    NSArray * repeatArray = @[@"星期日",@"星期一",@"星期二",@"星期三",@"星期四",@"星期五",@"星期六"];
                    MultiSelectedView *multi = [[MultiSelectedView alloc]initWithFrame:view.controller.view.bounds];
                    [view.controller.view addSubview:multi];
                    if (view.selectString!=nil) {
                        multi.defaultSelectString = view.selectString;
                    }
                    multi.multiSelectedHandle = ^(NSArray *data) {
                        NSArray *array = [data sortedArrayUsingSelector:@selector(compare:)];
                        NSString *string = array[0];
                        NSString *workDay;
                        if (data.count == 1) {
                            cell.detailLabel.text = string;
                            weakSelf.repeatString = cell.detailLabel.text;
                        } else {
                            for (int i = 1; i<array.count; i++) {
                                workDay = [NSString stringWithFormat:@"%@|%@",string,array[i]];
                                string = workDay;
                            }
                            cell.detailLabel.text = workDay;
                            weakSelf.repeatString = cell.detailLabel.text;
                        }
                        [view removeSelf];
                    };
                    [multi show:CGRectMake(20, (ScreenHeight-ScreenHeight/1.5)/2, ScreenWidth - 40, ScreenHeight/1.5) title:@"自定义" dataSource:repeatArray];
                    
                }
            } else {
                [view removeSelf];
            }
        }];
        if (self.dic.count > 0) {
            NSString *repeat = @"";
            if ([self.dic[@"repeat"] isEqualToString:@"星期一|星期二|星期三|星期四|星期五"]) {
                repeat =@"周一到周五";
            }else if ([self.dic[@"repeat"] isEqualToString:@"星期日|星期一|星期二|星期三|星期四|星期五|星期六"]) {
                repeat =@"每天";
            } else if ([self.dic[@"repeat"] isEqualToString:@"只响一次"]){
               repeat =@"只响一次";
            } else {
                repeat =@"自定义";
            }
            for (int i = 0; i < self.repeatArray.count; i ++) {
                
                if ([repeat isEqualToString:self.repeatArray[i]])
                {
                    public.defaulteSelectedIndex = i;
                }
            }
            if (public.defaulteSelectedIndex == 3) {
                public.selectString = self.dic[@"repeat"];
            }
        } else {
            public.defaulteSelectedIndex = 0;
        }
        
        [self.view addSubview:public];
        [public show:CGRectMake(20, (ScreenHeight-ScreenHeight/1.7)/2, ScreenWidth - 40, ScreenHeight/1.7) title:@"重复" dataSource:self.repeatArray];
    }
    
    if (indexPath.row == 1) {
        PublicView *public = [[PublicView alloc]initWithFrame:self.view.bounds];
        //-------
        public.controller = self;
        AddCustomTableViewCell * cell = (AddCustomTableViewCell * )[_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
        [public setSelectedCallback:^(NSInteger index,__weak PublicView *view) {
            cell.detailLabel.text = self.bellArray[index];
            self.bellString = cell.detailLabel.text;
            [view removeSelf];
            
        }];
        if (self.dic.count > 0) {
            for (int i = 0; i < self.bellArray.count; i ++) {
                if ([self.dic[@"bell"] isEqualToString:self.bellArray[i]])
                {
                    public.defaulteSelectedIndex = i;
                }
            }
        } else {
            public.defaulteSelectedIndex = 0;
        }
        [self.view addSubview:public];
        [public show:CGRectMake(20, (ScreenHeight-ScreenHeight/1.7)/2, ScreenWidth - 40, ScreenHeight/1.7) title:@"铃声" dataSource:self.bellArray];
    }
    
    
    if (indexPath.row == 2) {
        LabelView *labelView = [[LabelView alloc]initWithFrame:self.view.bounds];
        [labelView show:CGRectMake(20, (ScreenHeight-ScreenHeight/3.5)/2, ScreenWidth - 40, ScreenHeight/3.5)];
        [self.view addSubview:labelView];
        labelView.controller = self;
        [labelView setLabelViewCallback:^(NSString *info) {
            AddCustomTableViewCell * cell = (AddCustomTableViewCell * )[_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
            cell.detailLabel.text = info;
            self.labelString = info;
        }];
        
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (!self.isSelected) {
        return nil;
    }
    UIView * footerView =  [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 80)];
    [footerView addSubview:self.deleteButton];
    self.deleteButton.sd_layout
    .leftSpaceToView(footerView,10)
    .topSpaceToView(footerView,10)
    .rightSpaceToView(footerView,10)
    .bottomSpaceToView(footerView,10);
    self.titleLabel.text = @"编辑闹钟";
    return footerView;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (!self.isSelected) {
        return 0;
    }
    
    return 80;
}

#pragma mark - getter
- (UITableView *)tableView {
    if (_tableView) {
        return _tableView;
    }
    _tableView = [[UITableView alloc]init];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.35];
    _tableView.rowHeight = 80;
    return _tableView;
}

- (UIButton *)cancelButton {
    if (_cancelButton) {
        return _cancelButton;
    }
    _cancelButton = [UIButton buttonWithType:UIButtonTypeSystem];
    _cancelButton = [[UIButton alloc]init];
    _cancelButton.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
    [_cancelButton setImage:[UIImage imageNamed:@"取消"] forState:UIControlStateNormal];
    [_cancelButton addTarget:self action:@selector(cancelButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    return _cancelButton;
}

- (UIButton *)sureButton {
    if (_sureButton) {
        return _sureButton;
    }
    _sureButton = [UIButton buttonWithType:UIButtonTypeSystem];
    _sureButton = [[UIButton alloc]init];
    _sureButton.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
    [_sureButton setImage:[UIImage imageNamed:@"确定"] forState:UIControlStateNormal];
    [_sureButton addTarget:self action:@selector(sureButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    return _sureButton;
}

- (UILabel *)titleLabel {
    if (_titleLabel) {
        return _titleLabel;
    }
    _titleLabel = [[UILabel alloc]init];
    _titleLabel.text = @"新建闹钟";
    _titleLabel.textColor = [UIColor whiteColor];
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    _titleLabel.font = [UIFont systemFontOfSize:20 weight:0.01];
    return _titleLabel;
}

- (UIDatePicker *)datePicker {
    if (_datePicker) {
        return _datePicker;
    }
    _datePicker = [[UIDatePicker alloc]init];
    //日期控件格式（默认日期和时间）
    _datePicker.datePickerMode = UIDatePickerModeTime;
    _datePicker.backgroundColor = [UIColor clearColor];
    //本地化 (显示中文)
    _datePicker.locale = [[NSLocale alloc]initWithLocaleIdentifier:@"zh-CN"];
    return _datePicker;
}

- (UIButton *)deleteButton {
    if (_deleteButton) {
        return _deleteButton;
    }
    _deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
    //    _deleteButton.frame = CGRectMake(20, 10, scre, 60);
    [_deleteButton setTitle:@"删除闹钟" forState:UIControlStateNormal];
    [_deleteButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    _deleteButton.layer.masksToBounds = YES;
    _deleteButton.layer.cornerRadius = 10;
    _deleteButton.backgroundColor = [UIColor colorWithRed:0.2739 green:0.3892 blue:0.4957 alpha:1.0];
    [_deleteButton addTarget:self action:@selector(deleteButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    return _deleteButton;
}

-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

@end
